﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Windows.Media.Media3D;

using EQEmu.Database.Extensions;

namespace EQEmu.Doors
{
    public class DoorsCollectionChangedEventArgs : EventArgs
    {
        public IEnumerable<doors> AddedDoors { get; set; }
        public IEnumerable<doors> RemovedDoors { get; set; }
    }

    public class ZoneDoors
    {
        private string _zoneShortName;
        private int _zoneVersion;
        private ObservableCollection<doors> _doors = new ObservableCollection<doors>();
        private bool _hasModifications = false;

        public event EventHandler<DoorsCollectionChangedEventArgs> DoorsCollectionChanged;

        public ZoneDoors(string zoneName,int version=0)
        {
            _zoneShortName = zoneName;
            _zoneVersion = version;
            _doors.CollectionChanged += _doors_CollectionChanged;
        }

        public doors GetClosestDoor(Point3D point, double tolerance = 10.0)
        {
            doors door = null;

            foreach (var d in Doors)
            {
                if (Common.Functions.Distance(point, new Point3D(d.pos_x,d.pos_y,d.pos_z)) < tolerance)
                {
                    return d;
                }
            }

            return door;
        }

        public virtual void AddDoor(doors door)
        {
            _hasModifications = true;
            _doors.Add(door);
        }

        public virtual void RemoveDoor(doors door)
        {
            _hasModifications = true;
            _doors.Remove(door);
        }

        public virtual doors CreateDoor()
        {
            var door = new doors();
            door.zone = ZoneShortName;
            door.size = 100;
            return door;
        }

        void _doors_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
        {
            var e = DoorsCollectionChanged;
            if (e != null)
            {
                var arg = new DoorsCollectionChangedEventArgs()
                {
                    AddedDoors = args.NewItems != null ? args.NewItems.Cast<doors>() : null,
                    RemovedDoors = args.OldItems != null ? args.OldItems.Cast<doors>() : null
                };
                e(this, arg);
            }
        }

        public IEnumerable<doors> Doors
        {
            get { return _doors; }
        }

        public int ZoneVersion
        {
            get { return _zoneVersion; }
        }

        public string ZoneShortName
        {
            get { return _zoneShortName; }
            private set
            {
                _zoneShortName = value;
            }
        }

        public virtual bool HasModifications
        {
            get
            {
                return _hasModifications;
            }
        }
    }
}
